load("classpath:ext/db.js");

function sqlToolUsage() {
    console.info("usage: ");
    console.info("    ljs sql fileName db[pro.crm,fat.crm.1,dev.crm.corpId]");
}

function sqlMain(params) {
    if (params.length < 3) {
        sqlToolUsage();
        return;
    }
    var sql = getResourceContent(params[1].trim());

    var split = params[2].trim().split("\.");
    if (split.length < 2) {
        throw "evnConfig error : " + params[2];
    }

    var env = split[0].trim();
    var instance = split[1].trim();

    var dbSize = parseInt(jdbcProperties.getProperty(env + "." + instance + ".db.num", "1"));

    // 是否查询sql.
    var isSelect = sql.toLowerCase().contains("select ");

    for (var i = 0; i < dbSize; i++) {
        if (dbSize > 1 && split.length > 2 && parseInt(split[2]) % dbSize !== i) {
            continue;
        }

        var viewKey = instance;
        if (dbSize > 1) {
            viewKey += i % parseInt(jdbcProperties.getProperty(env + "." + instance + ".instance.num"));
            viewKey += "." + jdbcProperties.getProperty(env + "." + instance + ".db.name");
            viewKey += i % dbSize;
        }
        var envDbKey = env + "." + instance + (dbSize > 1 ?("." + i):"");
        if (isSelect) {
            var resultSet = mysql_query(envDbKey, sql);
            resultSet.forEach(function (value) {
                value.put("_db_env", envDbKey);
                console.info(value);
            });
        } else {
            var update = mysql_query(envDbKey, sql);
            console.info("{\"_db_env\":\"" + envDbKey + "\",\"update\":\"" + update + "\"}");
        }
    }
}

sqlMain(args);